﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Moonwish.Core.DataAccess;
using Moonwish.Core.EntityCore;
using Moonwish.Foundation.DataEntity;

namespace Moonwish.Foundation.DataAccess.SqlServer.ValueObjectClassCmd
{
    public class UpdateCommand : EntityCommand<V_FDT_ValueObjectClass>
    {
        public UpdateCommand(DbContext dbContext, List<V_FDT_ValueObjectClass> items, string userId)
            : base(dbContext, items, userId)
        {
        }

        public override void Execute()
        {
            var classSet = DbContext.Set<T_FDT_ValueObjectClass>();
            foreach (var item in Items)
            {
                if (item.ChangeTracker.State != ObjectState.Modified)
                {
                    throw new InvalidOperationException(String.Format("数据“{0}”不是修改状态，无法保存到数据库。", item.Name));
                }
                // 保存值对象分类
                var origalClass = classSet.Find(item.ValueObjectClassId);
                if (origalClass == null)
                {
                    throw new InvalidOperationException(String.Format("数据“{0}”不存在，无法保存到数据库。", item.Name));
                }
                origalClass.Name = item.Name;
                origalClass.Code = item.Code;
                origalClass.OrderNo = item.OrderNo;
                origalClass.Remark = item.Remark;
            }
            DbContext.SaveChanges();
        }
    }
}
